import React, { useState, FC } from "react";
import styled from "styled-components";
import {
  IComment,
  ISecondComment,
  cancelThumbsComment,
  thumbsComment,
  ThumbsCommentProps,
  transformThumbsComment,
} from "../../api/commentApi";
import { HeadPortraitBox } from "../../layout/Header";
import { userProfileRef } from "../../layout/UserProfile";
import { ThumbsState } from "../../pages/blog/[id]";
import { mongoIdToDate } from "../../utils";
import { ActiveLateY } from "../BUI/styled";
import { fadeIn } from "../commentStyled";
import RoleTag from "../common/RoleTag";
import Thumbs from "./Thumbs";

interface Props {
  comment: IComment | ISecondComment;
  userId: string;
  handleReply: any;
  reply?: string;
  commentIndex: number;
  commentId?: string; // 创建二级评论使用
}

const CommentItem: FC<Props> = ({
  comment: {
    _id,
    thumbsUp,
    thumbsDown,
    sender: [{ username, role, _id: at }],
    violation,
    content,
  },
  reply,
  userId,
  handleReply,
  commentIndex,
  commentId,
}) => {
  const [thumbsUps, setThumbsUps] = useState(thumbsUp);
  const [thumbsDowns, setThumbsDowns] = useState(thumbsDown);
  const [thumbsLoading, setThumbsLoading] = useState<ThumbsState>("");
  const thumbsState = thumbsUps.includes(userId)
    ? "UP"
    : thumbsDown.includes(userId)
    ? "DOWN"
    : "";
  //TODO 逻辑复杂待优化
  const handleThumbs = (type: ThumbsState) => async () => {
    if (!userId) return userProfileRef.current && userProfileRef.current.open();
    setThumbsLoading(type);
    const data: ThumbsCommentProps = { userId, commentId: _id, type };
    reply && (data.second = true);
    //有赞过
    if (thumbsState) {
      //取消赞过的
      if (thumbsState === type) {
        const result = await cancelThumbsComment(data);
        setThumbsLoading("");
        //没有data 或 code === -1
        if (!result.data || result.data.code) return;
        console.log("result:", result);
        if (type === "UP") {
          setThumbsUps(prev => prev.filter(id => id !== userId));
        } else {
          setThumbsDowns(prev => prev.filter(id => id !== userId));
        }
      } else {
        // 点击另一个
        const result = await transformThumbsComment({
          userId,
          commentId: _id,
          from: thumbsState,
          to: type,
          second: !!reply,
        });
        setThumbsLoading("");
        if (!result.data || result.data.code) return;
        if (type === "UP") {
          setThumbsUps(prev => [userId, ...prev]);
          setThumbsDowns(prev => prev.filter(id => id !== userId));
        } else {
          setThumbsUps(prev => prev.filter(id => id !== userId));
          setThumbsDowns(prev => [userId, ...prev]);
        }
      }
    } else {
      const result = await thumbsComment(data);
      setThumbsLoading("");
      //没有data 或 code === -1
      if (!result.data || result.data.code) return;
      console.log("result:", result);
      if (type === "UP") {
        setThumbsUps(prev => [userId, ...prev]);
      } else {
        setThumbsDowns(prev => [userId, ...prev]);
      }
    }
  };

  return (
    <>
      <CommentHead>
        <HeadPortraitBox>{username.substr(0, 2)}</HeadPortraitBox>
        <section>
          <span>
            {username} {role ? <RoleTag role={role} /> : null}
          </span>
          <code>{mongoIdToDate(_id).toLocaleString()}</code>
        </section>
      </CommentHead>
      <section>
        {violation ? (
          "评论违规"
        ) : (
          <>
            {reply ? <ReplySpan>@{reply}</ReplySpan> : ""}
            {content}
          </>
        )}
      </section>
      <CommentBottom>
        <span
          onClick={handleReply({
            commentId: commentId || _id,
            username,
            at,
            commentIndex,
          })}
        >
          回复
        </span>
        <Thumbs
          thumbsState={thumbsState}
          handleThumbs={handleThumbs}
          thumbsUp={thumbsUps.length}
          thumbsDown={thumbsDowns.length}
          thumbsLoading={thumbsLoading}
        />
      </CommentBottom>
    </>
  );
};

const ReplySpan = styled.span`
  color: ${props => props.theme.link};
  margin: 0 2px;
  cursor: pointer;
`;

export const SecondCommentBox = styled.div`
  margin-left: 4rem;
  display: flex;
  flex-wrap: wrap;
  border-radius: inherit;
  justify-content: space-between;

  & > div {
    margin: 0.5rem;
    @media (max-width: ${props => props.theme.media.phone}) {
      width: 100%;
    }
  }
`;

const CommentBottom = styled.div`
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding-right: 1rem;

  & > span:first-child {
    cursor: pointer;
    margin-right: 1rem;
    ${ActiveLateY};
  }
`;

const CommentHead = styled.div`
  display: flex;

  & > div:first-child {
    margin-left: 0;
    margin-right: 1rem;
  }

  & > section {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    span {
      display: flex;
      align-items: center;
    }
    code {
      color: #999;
    }
  }
`;

export const CommentBox = styled.div`
  animation: ${fadeIn} 0.4s linear;
  display: flex;
  flex-direction: column;
  margin: 1rem 0;
  box-shadow: 0 0 5px 0 #ccc;
  padding: 1rem;
  margin: inherit;
  border-radius: inherit;

  & > section {
    background: ${props => props.theme.shadow};
    padding: 1rem;
    margin: 1rem;
    margin-left: 4rem;
  }
`;

const Title = styled.span`
  font-weight: bold;
`;

export default CommentItem;
